package com.bugstack.springframework.beans.factory.support;

import com.bugstack.springframework.beans.BeansException;
import com.bugstack.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;


/**
 * 在这个类中具体的去实例化Bean
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

    //传入实例化对象函数
    private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition,Object [] args) {
        Object bean = null;
        try {
            bean = createBeanInstance(beanDefinition, beanName, args);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }

        addSingleton(beanName, bean);
        return bean;
    }


    //使用构造器创建bean的实例
    public Object createBeanInstance(BeanDefinition beanDefinition,String name,Object [] args){
        Constructor constructor = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
            Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
            for (Constructor<?> declaredConstructor : declaredConstructors) {
                if (null != args && declaredConstructor.getParameterTypes().length == args.length) {
                    constructor = declaredConstructor;
                    break;
                }
            }
            return getInstantiationStrategy().instantiate(beanDefinition,name,constructor,args);//返回实例化对象

    }

    //调用实例化对象函数
    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }
}
